package com.lanzhou.yuanfen.security.session;

import com.alibaba.fastjson.JSON;
import com.lanzhou.yuanfen.config.IpAddressContext;
import com.lanzhou.yuanfen.response.ServerResponseResult;
import com.lanzhou.yuanfen.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName: {@link SessionInformationExpiredStrategyImpl}
 * @Description: 会话信息过期处理
 * @author: Lanzhou
 * @date: 2020/5/28 19:24
 * @QQ: 1627518680
 * @Copyright:2020 All rights reserved.
 */
@Slf4j
@Component
public class SessionInformationExpiredStrategyImpl implements SessionInformationExpiredStrategy {


    @Resource
    private IpAddressContext ipAddressContext;

    /**
     * 当有过期会话时, 他访问接口后会自动调用当前方法
     * 参见 ConcurrentSessionFilter.doFilter()
     *
     * @param sessionInformationExpiredEvent
     * @throws IOException
     */
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent sessionInformationExpiredEvent) throws IOException {
        log.info("登录信息过期,可能是由于同一用户尝试多次登录!");
        HttpServletResponse response = sessionInformationExpiredEvent.getResponse();
        HttpServletRequest request = sessionInformationExpiredEvent.getRequest();
        // 清除Ip登入信息
        String ipAddress = RequestUtil.getIpAddress(request);
        ipAddressContext.removeAddress(ipAddress);
        if (!RequestUtil.isAjaxRequest(request)) {
            try {
                request.getRequestDispatcher("/loginPage").forward(request, response);
            } catch (ServletException e) {
                log.info("当前用户跳转登入页面失败..." + e);
            }
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            ServerResponseResult unauthorized = ServerResponseResult.error("登录信息过期,可能是由于同一用户尝试多次登录 !");
            out.write(JSON.toJSONString(unauthorized));
            out.flush();
            out.close();
        }
    }


}
